#include "cleanup.h"

cleanup::cleanup(QObject *parent) : QThread(parent)
{
}

void cleanup::clearVariables()
{
    cleanupList.clear();
    totalItemsCount = 0;
    _fileList.clear();
}

QList<cleanDataStruct*> cleanup::getCleanupList()
{
    return cleanupList;
}

void cleanup::calculate( const QString& path )
{
    QDir tempDir( path );
    QStringList nameFilters = mySettings::getRules();

    _fileList.append( tempDir.entryInfoList( nameFilters, QDir::AllDirs|QDir::Files|
                                                       QDir::Hidden |
                                                       QDir::NoDotAndDotDot ) );
    totalItemsCount += _fileList.size();

    QFileInfoList innerFolderList = tempDir.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot);
    for ( int i = 0; i < innerFolderList.size(); i++ )
        calculate( innerFolderList.at(i).absoluteFilePath() );
}

void cleanup::removeFiles()
{
    for (int i = 0; i < _fileList.size(); i++)
    {
        QFileInfo lFileInfo = _fileList.at(i);
        if ( lFileInfo.exists() )
        {
            qint64 _size = lFileInfo.size();
            if ( QFile::remove( lFileInfo.absoluteFilePath() ) )
            {
                if ( run_mode == 1 )//1 - USB drives
                {
                    int index = getCleanupListIndex( lFileInfo.absolutePath().left(3).replace( "/", "\\") );
                    if ( index > -1 )
                    {
                        cleanupList.at( index )->cleanedSize += _size;
                        cleanupList.at( index )->deletedItems++;
                    }
                }
                else
                {
                    cleanupList.at( 0 )->cleanedSize += _size;
                    cleanupList.at( 0 )->deletedItems++;
                }
            }
        }
        msleep(50);
        double factor = ((double)i)/((double)_fileList.size());
        emit makeStep( factor );
    }
}

void cleanup::setRunMode( int mode, QStringList pathList )
{
    // 1 - USB drives
    // 2 - Folder
    clearVariables();

    run_mode = mode;
    for ( int i = 0; i < pathList.size(); i++ )
    {
        cleanDataStruct *mySytruct = new cleanDataStruct();
        mySytruct->cleanPath = pathList.at(i);
        mySytruct->cleanedSize  = 0;
        mySytruct->deletedItems = 0;

        cleanupList.append(mySytruct);
    }
}

void cleanup::run()
{
    switch (run_mode)
    {
    case 1:
        {
            for ( int i = 0; i < cleanupList.size(); i++ )
                calculate( cleanupList.at(i)->cleanPath );
            break;
        }
    case 2:
        {
            calculate( cleanupList.at(0)->cleanPath );
            break;
        }
    }

    if ( totalItemsCount > 0 )
        removeFiles();
}

int cleanup::getCleanupListIndex( QString rootName )
{
    for ( int i = 0; i < cleanupList.size(); i++ )
    {
        if ( cleanupList.at(i)->cleanPath == rootName )
            return i;
    }
    return -1;
}
